#include "asycipc/server_runtime.hpp"

#include <vector>

namespace asycipc {

ServerConnection::ServerConnection(PipeServer& server, PipeHandlePtr handle,
                                   std::unique_ptr<Channel> channel)
    : server_(server), handle_(std::move(handle)), channel_(std::move(channel)) {}

bool ServerConnection::PumpOnce() {
  if (!handle_) {
    return false;
  }
  const auto payload = handle_->Read();
  if (payload.empty()) {
    return false;
  }

  auto control_frames = server_.ProcessInbound(*channel_, payload);
  WriteFrames(control_frames);

  auto maintenance_frames = server_.CollectMaintenanceFrames(*channel_);
  WriteFrames(maintenance_frames);
  return true;
}

void ServerConnection::FlushMaintenance() {
  WriteFrames(server_.CollectMaintenanceFrames(*channel_));
}

void ServerConnection::WriteFrames(const std::vector<Frame>& frames) {
  if (!handle_) {
    return;
  }
  for (const auto& frame : frames) {
    handle_->Write(frame.Serialize());
  }
}

}  // namespace asycipc
